import {
	WS_URL
} from "@/common/config.js"
import store from "@/store/index.js"
import {router} from "@/router/index.js" 
let isWebSocketOpen = false
export const createWebsocket = () => {
	if(isWebSocketOpen){
		return
	}
	uni.connectSocket({
		url: WS_URL,
		header: {
			'content-type': 'application/json'
		},
		success: () => {
			console.log("websocket connectSocket 接口调用成功---------")
		},
		fail: () => {
			console.warn("websocket connectSocket 接口调用失败---------")
		}
	});

	uni.onSocketOpen(function(res) {
		console.log('WebSocket连接已打开！');
		isWebSocketOpen = true
	});
	uni.onSocketError(function(res) {
		console.log('WebSocket连接打开失败，请检查！', res);
		isWebSocketOpen = false
		//重连
		setTimeout(()=>{
			createWebsocket()
		},2000)
	});
	uni.onSocketMessage(function(res) {
		if(JSON.parse(res.data).res.code==1){
			uni.$emit("websocketMessage", {
				data: JSON.parse(res.data)
			})
		}
		else if(JSON.parse(res.data).res.code== "401"){
			store.commit("user/logout")
			// router.push("/pages/login/login")
		}
		
	});
	uni.onSocketClose(function (res) {
		console.log("error trigger-------------",res)
		isWebSocketOpen = false
		//重连
		setTimeout(()=>{
			createWebsocket()
		},2000)
	});
}
export const sendSocketMessage = (msg) => {
	if (!isWebSocketOpen) {
		return
	}
	uni.sendSocketMessage({
		data: msg
	});
}
